package com.atguigu.gmall.common.config;

import com.atguigu.gmall.common.cache.BloomType;
import com.atguigu.gmall.common.constant.RedisConst;
import org.redisson.Redisson;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @ConditionalOnProperty ：配置文件中有指定的prefix.name的属性，并且值是havingValue指定的，则@Configuration生效
 * matchIfMissing = true：没配置就是true，不配就默认生效
 * redisson做出来的锁，API和JUC一样Redisson实现了lock()
 */
@ConditionalOnProperty(prefix = "redisson", name = "enable",
        havingValue = "true", matchIfMissing = true)
@Configuration
public class ItemServiceRedissonConfig {

    private static String ADDRESS_PREFIX = "redis://";

    /**
     * 写个配置类，将Redisson的客户端放入spring容器中
     *
     * @return
     */
    @Bean
    public RedissonClient redissonClient(RedisProperties redisProperties) {
        //redis:// or rediss://
        //RedissonClient redisson = Redisson.create(); //连接本地redis
        Config config = new Config();
        String host = redisProperties.getHost();
        int port = redisProperties.getPort();
        String password = redisProperties.getPassword();
        config.useSingleServer().setAddress(ADDRESS_PREFIX + host + ":" + port).setPassword(password);

        //config.setLockWatchdogTimeout(); 看门狗时间是用来自动续期的，

        RedissonClient redisson = Redisson.create(config);
        return redisson;
    }

    /**
     * 提前准备的布隆过滤器
     * 每一个bean的id就是方法名
     * @return
     */
    // @Primary
    @Bean(value = BloomType.SKU)
    public RBloomFilter<Object> skuFilter(RedissonClient redissonClient){
        //sku的布隆过滤器
        RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter(RedisConst.SKUKEY_PREFIX);
        /**
         * 布隆过滤器初始化，boolean tryInit(long expectedInsertions, double falseProbability);预期值，误判率
         */
        bloomFilter.tryInit(1000000L,0.001);
        return bloomFilter;
    }

    @Bean(value = BloomType.SPU)
    public RBloomFilter<Object> spuFilter(RedissonClient redissonClient){
        //sku的布隆过滤器
        RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter(RedisConst.USER_KEY_PREFIX);
        bloomFilter.tryInit(100000L,0.01);
        return bloomFilter;
    }
}
